import React from 'react';
import {Form, Row, Col, Select, Input, Button,Divider,Modal ,message} from 'antd';
import Grid from '../../components/table/grid';
import SCModal from '../../components/pickCity/SCModal';
import {withRouter} from 'react-router-dom'
import {sessionManager} from '../../utils/sessionStorage';
import { injectIntl } from 'react-intl';
import LogQueryModal from './logQueryModal';
import StubPicker from '../../components/pickCity/StubPicker';
import PickV from './pickV'
import AuthButton from '../../components/auth/authButton';

import axios from 'axios';
const FormItem = Form.Item;
const Option = Select.Option;
const createForm = Form.create;

@withRouter
class equipmentList extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            params: {},
			historyParams:{},
            refresh: 0,
			historyRefresh:0,
            options: [],
            TableData: [],
            logQuerySwitch:false,
            updatedHistoryVisible:false,
            changeS:false,
            updateVisible:false,
            changeStubType:false,
            selectedInfo:{},
			versionNumberData:{},
            stubId:'',
            defaultStubS:"04",
            version:[],
            version2:[],
            versionItem:undefined,
            versionItem2:undefined,
        };
		const powerStationManage = this.props.intl.messages.powerStationManage;
        const common = this.props.intl.messages.common;
        this.columns = [
            {
                title: common.powerStationName,
                dataIndex: 'stubGroupName',
                key: 'stubGroupName',
            },
            {
                title: common.EquipmentNo,
                dataIndex: 'id',
                key: 'id',
            }, {
                title: common.model,
                dataIndex: 'modelNo',
                key: 'modelNo',
            }, {
                title: common.type,
                dataIndex: 'type',
                key: 'type',
            }, {
                title: common.MaxPower,
                dataIndex: 'kw',
                key: 'kw',
            },
            {
                title:"固件类型",
                dataIndex: 'updateType',
                key: 'updateType',
            },
            {
                title: common.firmwareVersion,
                dataIndex: 'frameWork',
                key: 'frameWork',
            },
            {
                title: common.operation,
                key: 'operation',
                render: (text, record) => (
                    <span>
                        <span data-auth="003002003">
                            <a onClick={() => this.chargeOrder(text, record)}>{common.chargeOrder}</a>
                            <Divider type="vertical"/>
                        </span>
                        <a onClick={() => this.switchLogQuery(text,'logQuerySwitch')}>{common.logQuery}</a>
                        <span data-auth="003002005">
                            <Divider type="vertical"/>
                            <a onClick={() => this.switchLogQuery(text,'updateVisible')}>{common.remoteUpgrade}</a>
                        </span>
                        <span data-auth="003002007">
                            <Divider type="vertical"/>
                            <a onClick={() => this.switchLogQuery(text, 'updatStub')}>更新状态</a>
                        </span>
                        <span data-auth="003002009">
                            <Divider type="vertical"/>
                            <a onClick={() => this.switchLogQuery(text, 'updatStubType')}>修改类型</a>
                        </span>
                        <span data-auth="003002008">
                            <Divider type="vertical"/>
                            <a onClick={() => this.switchLogQuery(text, 'versionSearch')}>固件查询</a>
                        </span>
                        <span data-auth="003002006">
                            <Divider type="vertical"/>
                            <a onClick={() => this.switchLogQuery(text, 'updatedHistoryVisible')}>{common.upgradeHistory}</a>
                        </span>
                        <span>
                            <Divider type="vertical"/>
                            <a onClick={() => this.switchLogQuery(text, 'chargePermit')}>{common.upgradeHistory}</a>
                        </span>
                    </span>
                )
            }
            // {
            //     title: '当前状态',
            //     dataIndex: 'status',
            //     key: 'status',
            // },
        ];
        this.historyColumns = [
			{
				title: common.actingTime,
				dataIndex: 'otaStartTime',
				key: 'otaStartTime',
			},
			{
				title: powerStationManage.firmwareModel,
				dataIndex: 'stubModelNo',
				key: 'stubModelNo',
			},
			{
				title: '升级前版本',
				dataIndex: 'versionPre',
				key: 'versionPre',
			},
			{
				title: '升级后版本',
				dataIndex: 'versionAfter',
				key: 'versionAfter',
			},
			{
				title: '执行结果',
				key: 'status',
				render: (text) => {
					switch (text.status) {
						case 0:
							return '进行中';
						case 1:
							return '升级成功';
						case 2:
							return '升级失败('+text.endInfo+')';
						default:
							return ''
					}

				}
			},
			{
				title: '执行人',
				dataIndex: 'userName',
				key: 'userName',
			},
        ]
    }
    getRemoteInfo=()=>{
		axios.get('/api/stub/version/info',{ params:{stubId: this.state.stubId}}).then(res => {
		    console.log(res)
			if(res&&res.code===200){
				this.setState({
					versionNumberData: res.data
				});
				// this.freshGrid()
			}
		});
    }
    switchLogQuery=(text,modelId)=>{
        console.log(`text`,text);

        this.setState({
			[modelId]: true,
			stubId:text.id
        },()=>{
            switch (modelId) {
                case 'updateVisible':
                    this.setState({
                        versionItem2:undefined,
                        versionItem:undefined,
                    })
					this.getRemoteInfo();
					break;
                case 'updatedHistoryVisible':
					this.setState({
						historyParams: {
							stubId:text.id
                        }
					});
					break;
                case 'logQuerySwitch':
					this.setState({
						selectedInfo: text
					});
                    break;
                case 'updatStub':
                    this.setState({
                        selectedInfo:text,
                        changeS: true
                    });
                    break;
                case 'updatStubType':
                    this.setState({
                        selectedInfo:text,
                        changeStubType: true,
                        versionItem2:undefined,
                        versionItem:undefined,
                    });
                    break;
                case 'versionSearch':
                    axios.post('/api/stub/version/info',{stubId:this.state.stubId}).then(res=>{
                        if(res&&res.data){
                            message.success('命令成功下发')
                        }
                    })
                    break;
                case 'chargePermit':
                      this.props.history.push('/powerStation/chargePermit')
                      break;      
                default:
                    break
            }
        });

    }

    chargeOrder = (text) => {
        sessionManager.set('selectEquipment', text);
        this.props.history.push('/powerStation/equChargeOrder');
        this.props.form.resetFields();
    }
    transformData = (data) => {
        const common = this.props.intl.messages.common;
        if (data) {
            data.forEach((item) => {
                if (item.type == 0) {
                    item.type = common.AC
                }
                if (item.type == 1) {
                    item.type = common.DC
                }
                // item.status=currentStatus(item.status)
                item.key = item.id;
                return item
            });
        };
        return data
    }


    componentWillMount() {
        let selectStuGroupId = sessionManager.get('selectStuGroup').id;
        let stubGroupName = sessionManager.get('equipIDNAMEinfo').name||'';
        let stubGroupsId=sessionManager.get('equipIDNAMEinfo').id||'';
        console.log('获取的点击数据', selectStuGroupId, this.props.location.query);
        this.setState({
            params:Object.assign(this.state.params, {stubGroupId: selectStuGroupId}),
            stubGroupsId:stubGroupsId,
            stubGroupName:stubGroupName
        });
        this.getVersion()
    }

    getVersion=()=>{
        axios.post('/api/stub/firmware/list').then(res=>{
            if(res&&res.data){
                this.setState({
                    version:res.data
                })
            }
        })
    }

    closeLogQuery = (modelId) => {
        this.setState({
            [modelId]: false,
        });
    }
    //清空
    handleReset = () => {
        this.setState({
            params: {}
        })
        this.props.form.resetFields();
        sessionManager.clearItem('selectStuGroup')
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            values.stubGroupName=values.stubGroupName.currency;

            this.setState({
                params: {...values,stubGroupId:this.state.stubGroupsId},
                refresh: this.state.refresh + 1
            });
        });
    }
	// remoteUpgrade=()=>{
    //     console.log('remoteUpgrade');
	// 	axios.get('/api/stub/cmd/update',{ params:{
	// 			stubId: this.state.stubId,
	// 			typeId:this.state.versionNumberData.typeId,
	// 			version:this.state.versionNumberData.version
	// 		}}).then(res => {
	// 		console.log(res)
	// 		if(res&&res.code===200){
	// 			this.setState({
	// 				refresh: this.state.refresh + 1
	// 			});
	// 			this.closeLogQuery('remoteUpgrade')
	// 		}
	// 	});
    // }

    handleChange=(value)=> {
        console.log(`selected ${value}`);
        this.setState({
            defaultStubS:value
        })
    }

    getVersionItem=(value)=>{
        console.log(`versionItem ${value}`);
        this.setState({
            versionItem:value
        },this.getVersion2)
    }

    getVersion2Item=(value)=>{
        console.log(`versionItem2 ${value}`);
        this.setState({
            versionItem2:value
        })
    }

    getVersion2=()=>{
        axios.post('/api/stub/firmwareVersion/list',{id:this.state.versionItem}).then(res=>{
            if(res&&res.data){
                this.setState({
                    version2:res.data
                })
            }
        })
    }

    firmware=(value)=>{
        console.log(`12323 ${value}`);
    }

    confirmS=()=>{
        axios.post('/api/stub/staus/update',{status:this.state.defaultStubS,stubId:this.state.stubId}).then(res=>{
            if(res&&res.data){
                message.success('更新状态成功');
                this.setState({
                    changeS:false,
                    refresh:this.state.refresh+1
                })
            }
        })
    }

    PickVChange = (value, selectedOptions) => {
        //任意城市
       console.log(value, selectedOptions);
       this.setState({
           verison:value
       })
    };

    confirmType=()=>{
        if(!this.state.versionItem||!this.state.versionItem2){
            message.error('请选择固件型号以及固件版本');
            return
        }
        axios.post('/api/stub/stubType/update',{stubId:this.state.stubId,stubType:this.state.versionItem,version:this.state.versionItem2}).then(res=>{
            if(res&&res.data){
                message.success('修改类型成功');
                this.setState({
                    changeStubType:false
                })
            }
        })
    }

    updateRemote=()=>{
        debugger;
        if(!this.state.versionItem||!this.state.versionItem2){
            message.error('请选择固件型号以及固件版本');
            return
        }
        axios.post('/api/stub/cmd/update',{stubId:this.state.stubId,typeId:this.state.versionItem,version:this.state.versionItem2}).then(res=>{
            if(res&&res.data){
                message.success('远程升级成功');
                this.setState({
                    updateVisible:false
                })
            }
        })
    }
    render() {
        const {getFieldDecorator} = this.props.form;
		const common = this.props.intl.messages.common;
		const powerStationManage = this.props.intl.messages.powerStationManage;
        //多行数据操作
        const rowSelection = {
            onChange(selectedRowKeys, selectedRows) {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            onSelect(record, selected, selectedRows) {
                console.log('onSelect:', record, selected, selectedRows);
            },
            onSelectAll(selected, selectedRows, changeRows) {
                console.log('onSelectAll', selected, selectedRows, changeRows);
            },
        };
        let firmwareModel,versionNumber;
        if(this.state.versionNumberData&&this.state.versionNumberData.typeId){
			firmwareModel=this.state.versionNumberData.typeId;
			versionNumber=this.state.versionNumberData.version;
        }
        let updateButton=!(firmwareModel&&versionNumber);
        return (
            <div>
                <form form={this.props.form}>
                    <Row gutter={16}>
                      <Col xl={6} xxl={5}>
                            <FormItem
                            >
                                {getFieldDecorator(`stubGroupName`,{initialValue: {currency:this.state.stubGroupName}})(
                                    <StubPicker disabled={!!this.state.stubGroupName} url="/api/stubGroup/listForOption/qry" placeholder={this.state.stubGroupName}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={3}>
                            <FormItem
                            >
                                {getFieldDecorator('stubId', {})(
                                    <Input placeholder={common.EquipmentNo}/>
                                )}

                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem>
                                <Button style={{marginRight: 8}} className="ant-btn-84" onClick={this.handleReset}>{common.clear}</Button>
                                <Button type="primary"  className="ant-btn-84" onClick={this.handleSubmit}>{common.search}</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <Grid transformData={this.transformData} refresh={this.state.refresh} params={this.state.params}
                      columns={this.columns} url="/api/stub/qry"/>
                {/*日志查询*/}
                <LogQueryModal
                    visible={this.state.logQuerySwitch}
                    onCancel={()=>this.closeLogQuery('logQuerySwitch')}
                    selectedInfo={this.state.selectedInfo}
                />
                {/*远程升级*/}
				<SCModal  visible={this.state.updateVisible} handleCancel={()=>this.closeLogQuery('updateVisible')} title={common.remoteUpgrade} footer={null} width={400}>
                    <Select style={{width:200,marginRight:20}} onChange={this.getVersionItem} placeholder={'固件型号'}>
                        {this.state.version.map((k,v)=>(
                            <Option key={k.id} value={k.id}>{k.name}</Option>
                        ))}
                    </Select>
                    <br/>
                    <br/>
                    <Select style={{width:200,marginRight:20}} onChange={this.getVersion2Item} placeholder={'固件版本'}>
                        {this.state.version2.map((k,v)=>(
                            <Option key={k.version} value={k.version}>{k.version}</Option>
                        ))}
                    </Select>
                    <br/>
                    <br/>
                    <Button type={'primary'} className="ok-btn" onClick={this.updateRemote} >{'远程升级'}</Button>
				</SCModal>
                {/*升级履历*/}
                <SCModal visible={this.state.updatedHistoryVisible} handleCancel={()=>this.closeLogQuery('updatedHistoryVisible')} title={common.upgradeHistory} footer={null}>
					<Grid url="api/stub/update/his" columns={this.historyColumns} refresh={this.state.historyRefresh} params={this.state.historyParams}/>
                </SCModal>
                {/* 修改状态 */}
                <SCModal width={400} visible={this.state.changeS} handleCancel={()=>this.closeLogQuery('changeS')} title={'修改桩状态'} footer={null}>
					<Select style={{width:200,marginRight:20}} defaultValue={this.state.selectedInfo.status!==null&&this.state.selectedInfo.status!==undefined?this.state.selectedInfo.status.toString():this.state.defaultStubS} onChange={this.handleChange}>
                        <Option key={0} value={'04'}>{'维护中'}</Option>
                        <Option key={0} value={'05'}>{'离线'}</Option>
                        <Option key={0} value={'06'}>{'在建中'}</Option>
                    </Select>
                    <Button type={'primary'} className="ok-btn" onClick={this.confirmS} >{'修改'}</Button>
                </SCModal>
                {/* changeStubType 修改桩类型 */}
                <SCModal width={400} visible={this.state.changeStubType} handleCancel={()=>this.closeLogQuery('changeStubType')} title={'修改桩类型'} footer={null}>
                    <Select style={{width:200,marginRight:20}} onChange={this.getVersionItem} placeholder={'固件型号'}>
                        {this.state.version.map((k,v)=>(
                            <Option key={k.id} value={k.id}>{k.name}</Option>
                        ))}
                    </Select>
                    <br/>
                    <br/>
                    <Select style={{width:200,marginRight:20}} onChange={this.getVersion2Item} placeholder={'固件版本'}>
                        {this.state.version2.map((k,v)=>(
                            <Option key={k.version} value={k.version}>{k.version}</Option>
                        ))}
                    </Select>
                    <br/>
                    <br/>
                    <Button type={'primary'} className="ok-btn" onClick={this.confirmType} >{'修改类型'}</Button>
                </SCModal>
            </div>
        )
    }
}

//ant 表格验证需要创建表格-createForm
equipmentList = createForm()(equipmentList);
export default injectIntl(equipmentList)